/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.subrecord.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.mapper.AccountMapper;
import com.jeeplus.modules.account.service.AccountService;
import com.jeeplus.modules.centerrecord.entity.CenterRecord;
import com.jeeplus.modules.centerrecord.service.CenterRecordService;
import com.jeeplus.modules.dynamicrecord.entity.DynamicRecord;
import com.jeeplus.modules.dynamicrecord.service.DynamicRecordService;
import com.jeeplus.modules.freezingassets.entity.FreezingAssets;
import com.jeeplus.modules.freezingassets.mapper.FreezingAssetsMapper;
import com.jeeplus.modules.freezingassets.service.FreezingAssetsService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.orders.entity.Orders;
import com.jeeplus.modules.positionassets.entity.PositionAssets;
import com.jeeplus.modules.positionassets.mapper.PositionAssetsMapper;
import com.jeeplus.modules.positionassets.service.PositionAssetsService;
import com.jeeplus.modules.rewardparameters.entity.RewardParameters;
import com.jeeplus.modules.rewardparameters.mapper.RewardParametersMapper;
import com.jeeplus.modules.rewardparameters.service.RewardParametersService;
import com.jeeplus.modules.subgoods.entity.SubGoods;
import com.jeeplus.modules.subgoods.service.SubGoodsService;
import com.jeeplus.modules.traderecord.mapper.TradeRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.subrecord.entity.SubRecord;
import com.jeeplus.modules.subrecord.mapper.SubRecordMapper;

/**
 * 认购记录Service
 * @author w
 * @version 2021-03-26
 */
@Service
@Transactional(readOnly = true)
public class SubRecordService extends CrudService<SubRecordMapper, SubRecord> {
	@Autowired
	private AccountService accountService;
	@Autowired
	private SubGoodsService subGoodsService;
	@Autowired
	private FreezingAssetsService freezingAssetsService;
	@Autowired
	private FreezingAssetsMapper freezingAssetsMapper;
	@Autowired
	private PositionAssetsService positionAssetsService;
	@Autowired
	private PositionAssetsMapper positionAssetsMapper;
	@Autowired
	private MemberService memberService;
	@Autowired
	private DynamicRecordService dynamicRecordService;
	@Autowired
	private CenterRecordService centerRecordService;
	@Autowired
	private RewardParametersService rewardParametersService;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private RewardParametersMapper rewardParametersMapper;
	@Autowired
	private TradeRecordMapper tradeRecordMapper;

	public SubRecord get(String id) {
		return super.get(id);
	}
	
	public List<SubRecord> findList(SubRecord subRecord) {
		return super.findList(subRecord);
	}
	
	public Page<SubRecord> findPage(Page<SubRecord> page, SubRecord subRecord) {
		return super.findPage(page, subRecord);
	}
	
	@Transactional(readOnly = false)
	public void save(SubRecord subRecord) {
		super.save(subRecord);
	}
	
	@Transactional(readOnly = false)
	public void delete(SubRecord subRecord) {
		super.delete(subRecord);
	}
	public Double getTotalRecord() {
		return mapper.getTotalRecord();
	}
	/**
	 * 认购
	 * @param member
	 * @param goodsId
	 * @param num
	 * @return
	 */
	@Transactional(readOnly = false)
	public synchronized AjaxJson subscription (Member member, String goodsId, int num) {
		AjaxJson aj = new AjaxJson();
		Account account = accountService.get(member.getAccount().getId());
		if (account != null){
			SubGoods subGoods = subGoodsService.get(goodsId);
			if ("0".equals(subGoods.getIsSub())){
				try {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
					Date nowTime =df.parse(df.format(new Date()));

					Date beginTime = df.parse(subGoods.getStartTime());
					Date endTime = df.parse(subGoods.getEndTime());
					//调用判断方法是否在规定时间段内
					boolean isTime = DateUtils.timeCalendar(nowTime, beginTime, endTime);

					if (!isTime){
						aj.setSuccess(false);
						aj.setMsg("非认购时间！");
						return aj;
					}
				}catch (ParseException e){
					e.printStackTrace();
				}
			}else {
				aj.setSuccess(false);
				aj.setMsg("认购关闭！");
				return aj;
			}

			if (subGoods.getNum() >= num * 5){
				Double money = 5 * num * subGoods.getPrice();
				if (account.getYue() >= money){
					//商品减数量
					subGoods.setNum(subGoods.getNum()-(num * 5));
					subGoods.setStock(subGoods.getStock() + num*5);
					subGoodsService.save(subGoods);
					//给用户20%份额的提货券   减余额
					BigDecimal coupon = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(0.2));
					account.setExchangeCoupon(account.getExchangeCoupon()+(coupon.doubleValue()));
					account.setYue(account.getYue()-money);
					account.setBuy(account.getBuy()+money);
					account.preUpdate();
					accountMapper.update(account);
					//添加冻结40%
					BigDecimal f = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(0.4));
					BigDecimal fm = BigDecimal.valueOf(num*5).multiply(BigDecimal.valueOf(0.4));
					//如果之前有认购过此商品   有的话累加数量和金额
					FreezingAssets oldFreezing = new FreezingAssets();
					oldFreezing.setMember(member);
					oldFreezing.setSubGoods(subGoods);
					oldFreezing.setIsApply("0");
//					oldFreezing.setGoodsPrice(subGoods.getPrice());
					List<FreezingAssets> freezingAssetsList = freezingAssetsService.findList(oldFreezing);
					if (freezingAssetsList.size()>0){
						for (FreezingAssets freezingAssets : freezingAssetsList) {
							freezingAssets.setNum(freezingAssets.getNum()+fm.intValue());
							freezingAssets.setNowPrice(subGoods.getPrice());
							freezingAssets.setTotalPrice(freezingAssets.getGoodsPrice()*freezingAssets.getNum());
							freezingAssets.setNowTotal(freezingAssets.getNowPrice()*freezingAssets.getNum());
							freezingAssets.preUpdate();
							freezingAssetsMapper.update(freezingAssets);
						}
					}else {
						FreezingAssets freezingAssets = new FreezingAssets();
						freezingAssets.setId(IdGen.uuid());
						freezingAssets.setSubGoods(subGoods);
						freezingAssets.setGoodsName(subGoods.getGoodsName());
						freezingAssets.setGoodsPrice(subGoods.getPrice());
						freezingAssets.setMember(member);
						freezingAssets.setNowPrice(subGoods.getPrice());
						freezingAssets.setNowTotal(f.doubleValue());
						freezingAssets.setTotalPrice(f.doubleValue());
						freezingAssets.setNum(fm.intValue());
						freezingAssets.preInsert();
						freezingAssetsMapper.insert(freezingAssets);
					}

					//添加持仓40%
					PositionAssets oldPosition = new PositionAssets();
					oldPosition.setSubGoods(subGoods);
//					oldPosition.setGoodsPrice(subGoods.getPrice());
					oldPosition.setMember(member);
					oldPosition.setIsApply("0");
					List<PositionAssets> positionAssetsList = positionAssetsService.findList(oldPosition);
					if (positionAssetsList.size()>0){
						for (PositionAssets positionAssets : positionAssetsList) {
							positionAssets.setGoodsNum(positionAssets.getGoodsNum()+fm.intValue());
							positionAssets.setNowPrice(subGoods.getPrice());
							positionAssets.setTotalPrice(positionAssets.getGoodsPrice()*positionAssets.getGoodsNum());
							positionAssets.setNowTotal(positionAssets.getNowPrice()*positionAssets.getGoodsNum());
							positionAssets.preUpdate();
							positionAssetsMapper.update(positionAssets);
						}
					}else {
						PositionAssets positionAssets = new PositionAssets();
						positionAssets.setId(IdGen.uuid());
						positionAssets.setSubGoods(subGoods);
						positionAssets.setGoodsName(subGoods.getGoodsName());
						positionAssets.setGoodsNum(fm.intValue());
						positionAssets.setGoodsPrice(subGoods.getPrice());
						positionAssets.setMember(member);
						positionAssets.setNowPrice(subGoods.getPrice());
						positionAssets.setNowTotal(f.doubleValue());
						positionAssets.setTotalPrice(f.doubleValue());
						positionAssets.setIsApply("0");
						positionAssets.setApplyNum(0);
						positionAssets.preInsert();
						positionAssetsMapper.insert(positionAssets);
					}

					//添加认购记录
//					SubRecord oldSub = new SubRecord();
//					oldSub.setSubGoods(subGoods);
//					oldSub.setMember(member);
//					oldSub.setGoodsPrice(subGoods.getPrice());
//					List<SubRecord> subRecordList = findList(oldSub);
//					if (subRecordList.size()>0){
//						for (SubRecord subRecord : subRecordList) {
//							subRecord.setGoodsNum(subRecord.getGoodsNum()+(num * 5));
//							subRecord.setTotalPrice(subRecord.getGoodsNum()*subRecord.getGoodsPrice());
//							save(subRecord);
//						}
//					}else {
						SubRecord subRecord = new SubRecord();
						subRecord.setMember(member);
						subRecord.setSubGoods(subGoods);
						subRecord.setGoodsName(subGoods.getGoodsName());
						subRecord.setGoodsNum(num*5);
						subRecord.setGoodsPrice(subGoods.getPrice());
						subRecord.setTotalPrice(subRecord.getGoodsNum()*subRecord.getGoodsPrice());
						save(subRecord);
//					}
					//处理团队业绩和团队 认购收益
					manageTeam(member,money);
					centerRecordService.manageCenterRecord(member,subGoods,money);
					memberService.manageMemberType();
					aj.setSuccess(true);
					aj.setMsg("认购成功");
				}else {
					aj.setSuccess(false);
					aj.setMsg("账户余额不足");
				}
			}else {
				aj.setSuccess(false);
				aj.setMsg("商品数量不足");
			}
		}else {
			aj.setSuccess(false);
			aj.setMsg("账户信息有误");
		}
		return aj;
	}


	/**
	 * 处理团队业绩和认购收益
	 * @param member
	 * @param money
	 */
	@Transactional(readOnly = false)
	public void manageTeam(Member member, Double money) {
		//给上级添加业绩
		//团队业绩
		int flag1 = 0;
		int flag2 = 0;
		int flag3 = 0;
		Double sendMoney = 0.0;
		Double levelMoney = 0.0;
		String recordName = "";
		boolean isSend = false;
		//1星认购收益
		Double percentOne = 0.0;
		//2星认购收益
		Double percentTwo = 0.0;
		//3星认购收益
		Double percentThree = 0.0;
		//3星认购平级收益
		Double percentSameThree = 0.0;

		Integer count2 = 0;
		Integer count3 = 0;
		//查询平台总认购额
//		Double sumSub = mapper.findAllSubMoney();
		//平台总业绩
//		Double sumTeam = tradeRecordMapper.findAllTotal() * 0.1 + mapper.findAllSubMoney();
		if (member.getP() != null){
			Member pMember = memberService.get(member.getP().getId());
			if (pMember != null){
				//查询奖励比例
				List<RewardParameters> rewardParametersList = rewardParametersMapper.findList(new RewardParameters());
				if (rewardParametersList.size()>0){
					percentOne = rewardParametersList.get(0).getSubPercentOne();
					percentTwo = rewardParametersList.get(0).getSubPercentTwo();
					percentThree = rewardParametersList.get(0).getSubPercentThree();
					percentSameThree = rewardParametersList.get(0).getSubLevelThree();
					levelMoney = money*percentOne;
				}
				while (pMember != null){
					boolean isEffective = memberService.isOrNotEffective(pMember);

					Account account = accountService.get(pMember.getAccount().getId());
//					account.setTeam(account.getTeam()+money);

					if (("1".equals(pMember.getUsertype())  || "0".equals(pMember.getUsertype())) && isEffective){
						//只享受一代会员的收益
						if (flag1 == 0 && flag2 == 0 && flag3 == 0 && member.getP().getId().equals(pMember.getId())){
							sendMoney = money*percentOne;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "1星奖励";
							flag1 = 1;
							isSend = true;
						}else {
							isSend = false;
						}
					}else if ("2".equals(pMember.getUsertype()) && isEffective){
						if (flag2 == 0){
							count2 = memberService.findLevelCount(pMember);
							BigDecimal m = BigDecimal.valueOf(money*percentTwo).divide(BigDecimal.valueOf(count2+1),2,BigDecimal.ROUND_HALF_DOWN);
//							levelMoney = money*percentOne;
							sendMoney = m.doubleValue() + levelMoney;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "2星奖励";
							flag2 = 1;
							isSend = true;
						}else if (flag2 == 1){
							BigDecimal m = BigDecimal.valueOf(money*percentTwo).divide(BigDecimal.valueOf(count2+1),2,BigDecimal.ROUND_HALF_DOWN);
//							levelMoney = money*percentOne;
							sendMoney = m.doubleValue() + levelMoney;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "2星奖励";
//							flag2 = 1;
							isSend = true;
						}
						else {
							isSend = false;
						}
					}else if ("3".equals(pMember.getUsertype()) && isEffective || "1".equals(pMember.getIsService())){
						if (flag3 == 0){
							count3 = memberService.findLevelCount(pMember);
							BigDecimal m = BigDecimal.valueOf(money*percentThree).divide(BigDecimal.valueOf(count3+1),2,BigDecimal.ROUND_HALF_DOWN);
//							levelMoney = money*percentOne;
							sendMoney = m.doubleValue() + levelMoney;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "3星奖励";
							flag3 = 1;
							isSend = true;
						} else if (flag3 == 1){
							BigDecimal m = BigDecimal.valueOf(money*percentThree).divide(BigDecimal.valueOf(count3+1),2,BigDecimal.ROUND_HALF_DOWN);
							sendMoney = m.doubleValue() + levelMoney;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "3星奖励";
//							flag3 = 2;
							isSend = true;
						} else {
							isSend = false;
						}
					}else {
						isSend = false;
					}
//					accountService.save(account);

					if (isSend){
						accountMapper.saveTeamAndTeamProfit(money,sendMoney,account.getId());
						DynamicRecord dynamicRecord = new DynamicRecord();
						dynamicRecord.setFrommem(member);
						dynamicRecord.setMember(pMember);
						dynamicRecord.setMoney(sendMoney);
						dynamicRecord.setName(recordName);
						dynamicRecordService.save(dynamicRecord);
					}else {
						accountMapper.update(account);
					}
					//处理用户等级
//					memberService.manageMemberType(pMember);
					if (pMember.getP() != null){
						pMember = memberService.get(pMember.getP().getId());
					}else {
						break;
					}
				}
			}
		}





	}


	/**
	 * 处理团队业绩和认购收益(复投走)
	 * @param member
	 * @param money
	 */
	@Transactional(readOnly = false)
	public void manageTeam1(Member member, Double money) {
		//给上级添加业绩
		//团队业绩
		int flag1 = 0;
		int flag2 = 0;
		int flag3 = 0;
		Double sendMoney = 0.0;
		Double levelMoney = 0.0;
		String recordName = "";
		boolean isSend = false;
		//1星认购收益
		Double percentOne = 0.0;
		//2星认购收益
		Double percentTwo = 0.0;
		//3星认购收益
		Double percentThree = 0.0;
		//3星认购平级收益
		Double percentSameThree = 0.0;

		Integer count2 = 0;
		Integer count3 = 0;
		//查询平台总认购额
//		Double sumSub = mapper.findAllSubMoney();
		//平台总业绩
//		Double sumTeam = tradeRecordMapper.findAllTotal() * 0.1 + mapper.findAllSubMoney();
		if (member.getP() != null){
			Member pMember = memberService.get(member.getP().getId());
			if (pMember != null){
				//查询奖励比例
				List<RewardParameters> rewardParametersList = rewardParametersMapper.findList(new RewardParameters());
				if (rewardParametersList.size()>0){
					percentOne = rewardParametersList.get(0).getSubPercentOne();
					percentTwo = rewardParametersList.get(0).getSubPercentTwo();
					percentThree = rewardParametersList.get(0).getSubPercentThree();
					percentSameThree = rewardParametersList.get(0).getSubLevelThree();
					levelMoney = money*percentOne;
				}
				while (pMember != null){
					boolean isEffective = memberService.isOrNotEffective(pMember);

					Account account = accountService.get(pMember.getAccount().getId());
//					account.setTeam(account.getTeam()+money);

					if (("1".equals(pMember.getUsertype()) || "0".equals(pMember.getUsertype())) && isEffective){
						//只享受一代会员的收益
						if (flag1 == 0 && flag2 == 0 && flag3 == 0 && member.getP().getId().equals(pMember.getId())){
							sendMoney = money*percentOne;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "1星奖励";
							flag1 = 1;
							isSend = true;
						}else {
							isSend = false;
						}
					}else if ("2".equals(pMember.getUsertype()) && isEffective){
						if (flag2 == 0){
							count2 = memberService.findLevelCount(pMember);
							BigDecimal m = BigDecimal.valueOf(money*percentTwo).divide(BigDecimal.valueOf(count2+1),2,BigDecimal.ROUND_HALF_DOWN);
//							levelMoney = money*percentOne;
							sendMoney = m.doubleValue() + levelMoney;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "2星奖励";
							flag2 = 1;
							isSend = true;
						}else if (flag2 == 1){
							BigDecimal m = BigDecimal.valueOf(money*percentTwo).divide(BigDecimal.valueOf(count2+1),2,BigDecimal.ROUND_HALF_DOWN);
//							levelMoney = money*percentOne;
							sendMoney = m.doubleValue() + levelMoney;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "2星奖励";
//							flag2 = 1;
							isSend = true;
						}
						else {
							isSend = false;
						}
					}else if ("3".equals(pMember.getUsertype()) && isEffective || "1".equals(pMember.getIsService())){
						if (flag3 == 0){
							count3 = memberService.findLevelCount(pMember);
							BigDecimal m = BigDecimal.valueOf(money*percentThree).divide(BigDecimal.valueOf(count3+1),2,BigDecimal.ROUND_HALF_DOWN);
//							levelMoney = money*percentOne;
							sendMoney = m.doubleValue() + levelMoney;
							levelMoney = 0.0;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "3星奖励";
							flag3 = 1;
							isSend = true;
						} else if (flag3 == 1){
							BigDecimal m = BigDecimal.valueOf(money*percentThree).divide(BigDecimal.valueOf(count3+1),2,BigDecimal.ROUND_HALF_DOWN);
							sendMoney = m.doubleValue() + levelMoney;
							account.setYue(account.getYue()+sendMoney);
							account.setTodayTeam(account.getTodayTeam()+sendMoney);
							account.setTeamProfit(account.getTeamProfit()+sendMoney);
							account.setTodayProfit(account.getTodayProfit()+sendMoney);
							account.setTotalProfit(account.getTotalProfit()+sendMoney);
							recordName = "3星奖励";
//							flag3 = 2;
							isSend = true;
						} else {
							isSend = false;
						}
					}else {
						isSend = false;
					}
//					accountService.save(account);

					if (isSend){
						accountMapper.saveTeamAndTeamProfit(money,sendMoney,account.getId());
						DynamicRecord dynamicRecord = new DynamicRecord();
						dynamicRecord.setFrommem(member);
						dynamicRecord.setMember(pMember);
						dynamicRecord.setMoney(sendMoney);
						dynamicRecord.setName(recordName);
						dynamicRecordService.save(dynamicRecord);
					}else {
						accountMapper.update(account);
					}
					//处理用户等级
//					memberService.manageMemberType(pMember);
					if (pMember.getP() != null){
						pMember = memberService.get(pMember.getP().getId());
					}else {
						break;
					}
				}
			}
		}





	}

	public List<SubRecord> findListByDays(SubRecord subRecord) {
		return mapper.findListByDays(subRecord);
	}

	public Double getTodayRecord() {
		return mapper.getTodayRecord();
	}

	public Page<SubRecord> findTodayListPage(Page<SubRecord> page, SubRecord subRecord) {
		dataRuleFilter(subRecord);
		subRecord.setPage(page);
		page.setList(mapper.findTodayList(subRecord));
		return page;
	}

	public List<SubRecord> findLimitList(SubRecord subRecord) {
		return mapper.findLimitList(subRecord);
	}
}